import time
import asyncio
import redis
import redis.asyncio as aioredis

TOTAL = 1000  # 读取的 key 数量

# 同步读取 Redis
def sync_read_redis():
    r = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)

    start = time.time()
    for i in range(TOTAL):
        # 同步读取 user1: 开头的 key
        value = r.get(f"user1:{i}")
        # 如果需要可以打印或处理 value，这里为了性能暂时不打印
    print(f"[同步读取] 总耗时：{round(time.time() - start, 2)} 秒")

# 异步读取 Redis
async def async_read_redis():
    r = aioredis.Redis(host='localhost', port=6379, decode_responses=True)

    start = time.time()
    tasks = []
    for i in range(TOTAL):
        # 异步读取 user2: 开头的 key，构造协程任务
        tasks.append(r.get(f"user2:{i}"))
    results = await asyncio.gather(*tasks)
    # 可以在这里处理 results
    print(f"[异步读取] 总耗时：{round(time.time() - start, 2)} 秒")

    await r.aclose()

if __name__ == "__main__":
    print("开始测试 Redis 同步读取")
    sync_read_redis()

    print("\n开始测试 Redis 异步读取")
    asyncio.run(async_read_redis())
